package com.simple.simple_view.filter;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.simple.simple_view.domain.ResponseResult;
import com.simple.simple_view.domain.entity.Video;
import com.simple.simple_view.domain.system.SystemParam;
import com.simple.simple_view.domain.entity.LoginUser;
import com.simple.simple_view.domain.enums.AppHttpCodeEnum;
import com.simple.simple_view.utils.JWTUtil;
import com.simple.simple_view.utils.RedisCache;
import com.simple.simple_view.utils.WebUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

/*
 *@description: jwt过滤器
 *@author: hisen
 *@Time: 2023/10/28  20:27
 */
@Component
@Slf4j
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {
    @Resource
    private RedisCache redisCache;

    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
        //从请求头中获取token
        String token = httpServletRequest.getHeader("token");
        if(!StringUtils.hasText(token)){
            //说明该接口不需要登录  直接放行
            filterChain.doFilter(httpServletRequest, httpServletResponse);
            return;
        }
        //解析token
        Claims claims = null;
        try {
            claims = JWTUtil.parseJWT(token);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            ResponseResult result = ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
            WebUtil.renderString(httpServletResponse,result);
            return;
        }
        String userId = claims.getSubject();
        //从redis获取用户信息
        JSONObject loginUserObj= redisCache.getCacheObject(SystemParam.REDIS_LOGIN_PREFIX +userId);
        LoginUser loginUser = loginUserObj.toJavaObject(LoginUser.class);
        if (Objects.isNull(loginUser))
        {
            //token失效或者超时，需要重新登录
            ResponseResult result = ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
            WebUtil.renderString(httpServletResponse, result);
            return;
        }
        //set SecurityContextHolder
        UsernamePasswordAuthenticationToken authenticationToken=new UsernamePasswordAuthenticationToken(loginUser,null,null);
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        //放行
        filterChain.doFilter(httpServletRequest,httpServletResponse);
    }
}